//
//  XMBagListViewController.m
//  XunMi
//
//  Created by MacBook on 2024/2/29.
//  Copyright © 2024 TieZhu. All rights reserved.
//

#import "XMTaskListViewController.h"
#import "XMTaskListHeaderView.h"
#import "XMTaskListTableViewCell.h"
#import "XMTaskModel.h"
#import "XMRealViewController.h"
#import "XMInviteViewController.h"
#import "XMDynamicUploadViewController.h"
#import "XMBindPhoneLoginViewController.h"
#import "XMRecentPhotosListViewController.h"
#import "XMEditUserViewController.h"


@interface XMTaskListViewController () <UITableViewDataSource, UITableViewDelegate>
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray<XMTaskModel *> *dataArray;
@property (nonatomic, strong) XMTaskListHeaderView *headerView;
@end


@implementation XMTaskListViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.dataArray = [NSMutableArray array];
    [self setupSubviews];
    
    XMWeakSelf(self);
    self.headerView.gotoBlock = ^(XMTaskModel * _Nonnull model) {
        XMStrongSelf(self);
        if (model.handle_status.intValue == 1) {
            [self handleTask:model.task_id];
        }
        if (model.handle_status.intValue == 0 && ![XMUtil isBlankString:model.client_event_name]) {
            NSString *type = model.client_event_name;
            if ([type isEqualToString:@"实名认证"]) {
                XMRealViewController *vc = [[XMRealViewController alloc] initWithNibName:kStringFromClass(XMRealViewController) bundle:nil];
                [self.navigationController pushViewController:vc animated:YES];
            }
        }
    };
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self listData];
}

- (void)handleTask:(NSString *)taskId {
    [MBProgressHUD showHUDActivityMsg:nil toView:kWindow];
    NSMutableDictionary *dic = @{
        @"task_id": taskId
    }.mutableCopy;
    
    [YHNetworkManager.sharedInstance postWithUrl:@"api/activity/task/handle" parameters:dic completeBlock:^(XMResponseTip * _Nonnull tip, id  _Nullable result) {
        if (tip.success) {
            [MBProgressHUD hideHUD];
            [MBProgressHUD showHUDMsg:@"领取成功" toView:nil];
            [self listData];
        }
    }];
}

#pragma mark - setupSubviews
- (void)setupSubviews {
    self.view.backgroundColor = kHEX(@"#F2F2F2");
    self.tableView.backgroundColor = kHEX(@"#F2F2F2");
    
    [self.view addSubview:self.tableView];
    [self.tableView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.view).insets(UIEdgeInsetsMake(0, 0, kBottomSafeHeight, 0));
    }];
    
    [self.tableView registerNib:kNibWithName(kStringFromClass(XMTaskListTableViewCell)) forCellReuseIdentifier:kStringFromClass(XMTaskListTableViewCell)];
    
    if (self.type == 1) {
        UIView *header = [[UIView alloc] initWithFrame:kFRAME(0, 0, kScreenWidth, 148)];
        self.headerView = [XMTaskListHeaderView viewFromXib];
        self.tableView.tableHeaderView = header;
        [header addSubview:self.headerView];
    }
}

- (void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];
    if (self.type == 1) {
        self.headerView.frame = kFRAME(0, 0, kScreenWidth, 148);
    }
}

#pragma mark - listData
- (void)listData {
    NSMutableDictionary *dic = @{
        @"task_mode": @(self.type)
    }.mutableCopy;
    [YHNetworkManager.sharedInstance postWithUrl:@"api/activity/task/detail" parameters:dic completeBlock:^(XMResponseTip * _Nonnull tip, id  _Nullable result) {
        if (tip.success) {
            self.dataArray = [XMTaskModel mj_objectArrayWithKeyValuesArray:result[@"record"]];
            if (result[@"certify_data"]) {
                self.headerView.model = [XMTaskModel mj_objectWithKeyValues:result[@"certify_data"]];
            }
            [self.tableView reloadData];
        }
    }];
}

#pragma mark - UITableViewDataSource & UITableViewDelegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataArray.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 77;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    XMTaskListTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kStringFromClass(XMTaskListTableViewCell)];
    if (self.dataArray.count > 0) {
        cell.model = self.dataArray[indexPath.row];
    }
    
    XMWeakSelf(self);
    cell.gotoBlock = ^(XMTaskModel * _Nonnull model) {
        XMStrongSelf(self);
        if (model.handle_status.intValue == 1) {
            [self handleTask:model.task_id];
        }
        
        if (model.handle_status.intValue == 0 && ![XMUtil isBlankString:model.client_event_name]) {
            NSString *type = model.client_event_name;
            
            if ([type isEqualToString:@"邀请实名认证"]) {
                XMInviteViewController *vc = [[XMInviteViewController alloc] initWithNibName:kStringFromClass(XMInviteViewController) bundle:nil];
                [self.navigationController pushViewController:vc animated:YES];
            }
            
            if ([type isEqualToString:@"绑定手机"]) {
                XMBindPhoneLoginViewController *vc = [[XMBindPhoneLoginViewController alloc] initWithNibName:kStringFromClass(XMBindPhoneLoginViewController) bundle:nil];
                [self.navigationController pushViewController:vc animated:YES];
            }
            
            if ([type isEqualToString:@"完善资料"] ||
                [type isEqualToString:@"语音签名"]) {
                XMEditUserViewController *vc = [[XMEditUserViewController alloc] init];
                [self.navigationController pushViewController:vc animated:YES];
            }
            
            if ([type isEqualToString:@"发布动态"]) {
                XMDynamicUploadViewController *vc = [[XMDynamicUploadViewController alloc] initWithNibName:kStringFromClass(XMDynamicUploadViewController) bundle:nil];
                [self.navigationController pushViewController:vc animated:YES];
            }
            
            if ([type isEqualToString:@"动态点赞"]) {
                [self selectedTabIndex:1];
            }
            
            if ([type isEqualToString:@"关注"] ||
                [type isEqualToString:@"发起语音"] ||
                [type isEqualToString:@"发起视频"]) {
                [self selectedTabIndex:0];
            }
            
            if ([type isEqualToString:@"上传相册"]) {
                XMRecentPhotosListViewController *vc = [[XMRecentPhotosListViewController alloc] initWithNibName:kStringFromClass(XMRecentPhotosListViewController) bundle:nil];
                [self.navigationController pushViewController:vc animated:YES];
            }
            
        }
    };
    
    return cell;
    
}

- (void)selectedTabIndex:(NSInteger)index {
    UITabBarController *tabBarController = [UIViewController currentViewController].tabBarController;
    if (tabBarController.viewControllers.count <= index) {
        return;
    }
    UINavigationController *navigationController = [UIViewController currentNavigatonController];
    if (tabBarController.selectedIndex != index) {
        [tabBarController setSelectedIndex:index];
    }
    [navigationController popToRootViewControllerAnimated:NO];
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return CGFLOAT_MIN;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return CGFLOAT_MIN;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    return nil;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    return nil;
}

#pragma mark - JXCategoryListContentViewDelegate
- (UIView *)listView {
    return self.view;
}

#pragma mark - Getter
- (UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
        if (@available(iOS 11.0, *)) {
            _tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
            _tableView.contentInset = UIEdgeInsetsMake(0, 0, 0, 0);
            _tableView.scrollIndicatorInsets = UIEdgeInsetsMake(0, 0, 0, 0);
        }
        _tableView.dataSource = self;
        _tableView.delegate = self;
        _tableView.backgroundColor = UIColor.clearColor;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.tableHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 0, CGFLOAT_MIN)];
        _tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 0, CGFLOAT_MIN)];
        
        _tableView.estimatedRowHeight = CGFLOAT_MIN;
        _tableView.estimatedSectionFooterHeight = CGFLOAT_MIN;
        _tableView.estimatedSectionHeaderHeight = CGFLOAT_MIN;
        _tableView.rowHeight = UITableViewAutomaticDimension;
    }
    return _tableView;
}

@end
